using UnityEngine;

namespace CGF
{
    /// <summary>
    /// 直线方程类,用于计算数据的线性关系
    /// </summary>
    public class Line
    {
        public float k, b;
        public Vector2 p1, p2;
        public float radian;

        public Line() { }

        public Line(Vector2 point1, Vector2 point2)
        {
            SetData(point1, point2);
        }

        public Line(float x1, float y1, float x2, float y2)
        {
            SetData(x1, y1, x2, y2);
        }

        public Line(Vector2 point, float radian)
        {
            SetData(point, radian);
        }

        public void SetData(Vector2 point1, Vector2 point2)
        {
            SetData(point1.x, point1.y, point2.x, point2.y);
        }

        public void SetData(float x1, float y1, float x2, float y2)
        {
            this.p1 = new Vector2(x1, y1);
            this.p2 = new Vector2(x2, y2);
            k = x2 - x1 == 0 ? 0 : (y2 - y1) / (x2 - x1);
            b = y1 - k * x1;
            radian = Mathf.Atan2(y2 - y1, x2 - x1);
        }

        public void SetData(Vector2 point, float radian)
        {
            this.p1 = point;
            this.p2.x = this.p1.x + Mathf.Cos(radian);
            this.p2.y = this.p1.y + Mathf.Sin(radian);
            k = p2.x - point.x == 0 ? 0 : (p2.y - point.y) / (p2.x - point.x);
            b = point.y - k * point.x;
            this.radian = radian;
        }

        public float GetX(float y)
        {
            return k == 0 ? 0 : (y - b) / k;
        }

        public float GetY(float x)
        {
            return k * x + b;
        }
    }
}
